/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sjtu.servlet;

import com.sjtu.bean.CommentBean;
import com.sjtu.bean.UserBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author p w
 */
public class GetCommentServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doWork(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doWork(request, response);
    }

    public void doWork(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String obj = request.getParameter("obj");
        JSONObject jsonObj = null;
        try {
            jsonObj = new JSONObject(obj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        PrintWriter writer = response.getWriter();
        try {
            int bookId = jsonObj.getInt("bookId");
            String userName = jsonObj.getString("userName");
//            System.out.println("aaa"+username+password);
            ArrayList<CommentBean> comment = CommentBean.getComment(bookId, userName);
            ArrayList<Integer> userIdList = new ArrayList<Integer>();
            ArrayList<String> userNameList = new ArrayList<String>();
            ArrayList<String> commentList = new ArrayList<String>();
            ArrayList<Date> dateList = new ArrayList<Date>();
            ArrayList<Integer> scoreList = new ArrayList<Integer>();
            JSONObject jsonRes = new JSONObject();
            for (int i = 0; i < comment.size(); i++) {
                userIdList.add(comment.get(i).getUserId());
                commentList.add(comment.get(i).getContent());
                dateList.add(comment.get(i).getCreateDate());
                scoreList.add(comment.get(i).getScore());
            }
            for (int i = 0; i < userIdList.size(); i++) {
                userNameList.add(UserBean.getUser(userIdList.get(i)).getName());
            }
            jsonRes.put("userNameList", userNameList);
            jsonRes.put("commentList", commentList);
            jsonRes.put("scoreList", scoreList);
            jsonRes.put("dateList", dateList);
            writer.write(jsonRes.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        writer.flush();
        writer.close();
    }
}
